<template>
  <div class="wrap-container">
    <div class="search_box">
      <div class="search_tit">场地查询</div>
      <el-form :inline="true" label-position="left" label-width="76px">
        <el-form-item label="场馆名称">
          <el-input
            clearable
            v-model="queryParams.stadiumName"
            placeholder="请输入场馆名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="场馆类型">
          <el-select filterable v-model="queryParams.type" placeholder="请选择" clearable>
            <el-option
              :label="item.dictLabel"
              :value="item.dictValue"
              v-for="item in dictTypeList"
              :key="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-select filterable v-model="queryParams.enable" placeholder="请选择" clearable>
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="item in statusList"
              :key="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="市辖区">
          <el-cascader
            filterable
            clearable
            :options="areaTree"
            v-model="addressId"
            @change="handleChange"
            placeholder="请选择区域"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="创建日期">
          <el-date-picker
            v-model="queryParams.createTime"
            type="date"
            placeholder="请选择"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table_box">
      <div class="tabs_box">
        <el-tabs v-model="tabsVal" @tab-change="handleClick">
          <el-tab-pane
            :label="`${item.label}`"
            :name="item.value"
            v-for="item in tabsList"
            :key="item.value"
          >
            <template #label> {{ item.label }} ({{ item.count }}) </template>
          </el-tab-pane>
        </el-tabs>
        <div class="handle_btn">
          <el-button class="del_btn" @click="handleDel(1)">批量删除</el-button>
        </div>
      </div>
      <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50"> </el-table-column>
        <el-table-column label="序号" width="80">
          <template #default="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="区域" prop="areaName" width="120" />
        <el-table-column label="场馆名称" prop="stadiumName" show-overflow-tooltip width="260" />
        <el-table-column label="场馆类型" prop="type" />
        <el-table-column label="启用状态" prop="enable">
          <template #default="{ row }">
            <span :class="{ 'text-color-D43030': row.enable == 0 }">{{
              row.enable == 1 ? '启用' : '停用'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" prop="approval">
          <template #default="{ row }">
            <div class="flex items-center" v-if="row.approval == 0">
              <i class="block w-3px h-3px bg-color-0988FB rounded-full mr-5px"></i>
              <span style="color: #0988fb">待审核</span>
            </div>
            <div class="flex items-center" v-else-if="row.approval == 1">
              <i class="block w-3px h-3px bg-color-43CF7C rounded-full mr-5px"></i>
              <span style="color: #43cf7c">审核通过</span>
            </div>
            <div class="flex items-center" v-else-if="row.approval == 2">
              <i class="block w-3px h-3px bg-color-D43030 rounded-full mr-5px"></i>
              <span style="color: #d43030">审核失败</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="审核人" prop="approvalUser" />
        <el-table-column
          label="备注"
          prop="rejectRemark"
          width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="{ row }">
            <div v-if="row.approval == 2">
              <el-button
                type="danger"
                size="small"
                @click="handleDetail(row.stadiumId)"
                v-hasPermi="['sys:approval:btn_site_view']"
                >备注</el-button
              >
            </div>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" />
        <el-table-column label="更新时间" prop="updateTime" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <div class="table_btn">
              <el-button
                class="primary_text"
                type="text"
                @click="handleDetail(row.stadiumId)"
                v-hasPermi="['sys:approval:btn_site_view']"
                >详情</el-button
              >
              <el-button
                type="text"
                @click="handleDel(0, row.stadiumId)"
                v-hasPermi="['sys:approval:btn_site_del']"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { listData } from '@/api/system/dict/data'
import { getApprovalSiteList, getApprovalSiteCount, delSiteByStadiumId } from '@/api/site/site'
import { getAreaTree } from '@/api/stadium/stadium'
import { ElMessage, ElMessageBox } from 'element-plus'

// 定义类型
interface QueryParams {
  pageNum: number
  pageSize: number
  stadiumName: string | null
  type: string | null
  createTime: string | null
  areaName: string | null
  enable: number | null
}

interface TabItem {
  label: string
  value: string
  count: number
}

interface TableDataItem {
  stadiumId: number
  areaName: string
  stadiumName: string
  type: string
  enable: number
  approval: number
  approvalUser: string
  rejectRemark: string
  createTime: string
  updateTime: string
}

interface DictTypeItem {
  dictLabel: string
  dictValue: string
}

interface StatusItem {
  label: string
  value: number
}

interface AreaTreeItem {
  value: string
  label: string
  children?: AreaTreeItem[]
}

// 使用 vue-router
const router = useRouter()

// 响应式数据
const loading = ref(false)
const dictTypeList = ref<DictTypeItem[]>([])
const areaTree = ref<AreaTreeItem[]>([])
const addressId = ref<string[]>([])
const total = ref(0)
const tabsVal = ref('-1')
const tableData = ref<TableDataItem[]>([])
const multipleSelection = ref<TableDataItem[]>([])

const queryParams = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 10,
  stadiumName: null,
  type: null,
  createTime: null,
  areaName: null,
  enable: null,
})

const tabsList = ref<TabItem[]>([
  { label: '全部', value: '-1', count: 0 },
  { label: '待审核', value: '0', count: 0 },
  { label: '审核完成', value: '1', count: 0 },
  { label: '审核失败', value: '2', count: 0 },
])

const statusList = ref<StatusItem[]>([
  {
    label: '启用',
    value: 1,
  },
  {
    label: '停用',
    value: 0,
  },
])

// 方法定义
// 订单列表
const getList = async () => {
  loading.value = true
  try {
    const res: any = await getApprovalSiteList({
      ...queryParams,
      approval: tabsVal.value == '-1' ? '' : tabsVal.value,
    })
    tableData.value = res.rows
    total.value = res.total
  } finally {
    loading.value = false
  }
}

// 订单统计
const getCount = async () => {
  const { data }: any = await getApprovalSiteCount(queryParams)
  if (tabsList.value[0]) tabsList.value[0].count = data.countAll
  if (tabsList.value[1]) tabsList.value[1].count = data.countDsh
  if (tabsList.value[2]) tabsList.value[2].count = data.countYwc
  if (tabsList.value[3]) tabsList.value[3].count = data.countBh
}

//获取场馆类型
const getDictTypeList = async () => {
  const params = {
    pageNum: 1,
    pageSize: 99,
    dictType: 'site_type',
  }
  const res: any = await listData(params)
  dictTypeList.value = res.rows
  dictTypeList.value.unshift({ dictLabel: '综合', dictValue: '0' })
}

// 获取省市区数据
const getArea = async () => {
  const { data } = await getAreaTree()
  areaTree.value = data
}

// 省市区选择
const handleChange = (value: any) => {
  if (value && value.length >= 3) {
    queryParams.areaName = value[2]
  } else {
    queryParams.areaName = null
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
  getCount()
}

// 重置
const reset = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    stadiumName: null,
    type: null,
    createTime: null,
    areaName: null,
    enable: null,
  })
  addressId.value = []
  getList()
  getCount()
}

// 选项卡切换
const handleClick = () => {
  queryParams.pageNum = 1
  getList()
}

// 表格多选
const handleSelectionChange = (val: TableDataItem[]) => {
  multipleSelection.value = val
}

// 查看详情
const handleDetail = (id: number) => {
  router.push({
    path: '/approval/siteApprovalDetail',
    query: { id: String(id) },
  })
}

// 删除
const handleDel = async (type: number, id?: number) => {
  let ids = ''
  if (type == 1) {
    ids = multipleSelection.value.map((item) => item.stadiumId).join(',')
  } else {
    ids = String(id)
  }
  if (ids == '') {
    ElMessage.error('请选择要删除的数据')
    return
  }
  try {
    await ElMessageBox.confirm('是否确认删除选中的数据项？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await delSiteByStadiumId({ stadiumId: ids })
    getList()
    getCount()
    ElMessage.success('删除成功')
  } catch (error) {
    // 用户取消删除或请求失败
  }
}

// 新增场馆
const goAddStadium = () => {
  router.push({ path: '/stadium/add' })
}

// 生命周期
onMounted(() => {
  getList()
  getCount()
  getDictTypeList()
  getArea()
})
</script>

<style lang="scss" scoped>
.search_box {
  padding-bottom: 9px;
  .el-button + .el-button {
    margin-left: 14px !important;
  }
  .el-form-item {
    margin-bottom: 14px;
  }
}
.table_box {
  position: relative;
  padding-top: 6px;
  .tabs_box {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    margin-bottom: 15px;
    :deep(.el-tabs) {
      flex: 1;
      .el-tabs__header {
        margin: 0;
      }
    }
  }
  .handle_btn {
    margin-left: 35px;
    .el-button {
      padding: 0;
      width: 90px;
      height: 35px;
      line-height: 35px;
    }
  }
}
:deep(.el-table .el-table__body td .cell .line-limit-length:empty::after) {
  content: '--';
}
</style>
